package com.rech.xbexpress3;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.RecyclerView;
import com.rech.utils.OtherUtil;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.rech.xbexpress3.R;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.File;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class SettingActivity extends AppCompatActivity {
    private String _sn;
    private CountDownTimer mTimer=null; //UI业务倒计时
    private int count = 30;
    private EditText etFace;
    /**
     * Whether or not the system UI should be auto-hidden after
     * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
     */
    private static final boolean AUTO_HIDE = true;

    /**
     * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
     * user interaction before hiding the system UI.
     */
    private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

    /**
     * Some older devices needs a small delay between UI widget updates
     * and a change of the status and navigation bar.
     */
    private static final int UI_ANIMATION_DELAY = 300;
    private final Handler mHideHandler = new Handler();

    private final Runnable mHidePart2Runnable = new Runnable() {
        @SuppressLint("InlinedApi")
        @Override
        public void run() {
            // Delayed removal of status and navigation bar


        }
    };
    private final Runnable mShowPart2Runnable = new Runnable() {
        @Override
        public void run() {
            // Delayed display of UI elements
            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) {
                actionBar.show();
            }
        }
    };
    private boolean mVisible;
    private final Runnable mHideRunnable = new Runnable() {
        @Override
        public void run() {
            hide();
        }
    };
    /**
     * Touch listener to use for in-layout UI controls to delay hiding the
     * system UI. This is to prevent the jarring behavior of controls going away
     * while interacting with activity UI.
     */
    private final View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (AUTO_HIDE) {
                delayedHide(AUTO_HIDE_DELAY_MILLIS);
            }
            return false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedPreferences sharedPreferences = getSharedPreferences("xbbox", Context.MODE_PRIVATE);
        String orientation = sharedPreferences.getString("Orientation","");
        if (orientation.equals("landscape")) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }

        //eventbus
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        setContentView(R.layout.activity_setting);
        etFace = findViewById(R.id.et_face);
        etFace.setText(Math.round(sharedPreferences.getFloat("faceAccuracy", 40f)) + "");
        TextView  verText = (TextView) findViewById(R.id.verText);
        String verInfo = OtherUtil.getInstance().getAppVersion() +" "+ OtherUtil.getInstance().getAppSerial(OtherUtil.getMainContext());
        verText.setText(verInfo);
        //

        mVisible = true;getSupportActionBar().hide();
        findViewById(R.id.step1).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,0));
        findViewById(R.id.step2).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));

        Button admin_back_btn = (Button) findViewById(R.id.admin_back);
        admin_back_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Exit();
                finish();
            }
        });
        Button admin_login_btn = (Button) findViewById(R.id.admin_login);
        admin_login_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText passwordEdit = findViewById(R.id.admin_password);
                String password = passwordEdit.getText().toString();
                if(password.equals("20200501")){
                    count = 180;
                    findViewById(R.id.step1).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
                    findViewById(R.id.step2).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,0));

                }
            }
        });
        Button set_btn = (Button) findViewById(R.id.setbtn);
        set_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (etFace.getText().toString().trim().equals("") || Float.parseFloat(etFace.getText().toString().trim()) > 100f) {
                    Toast.makeText(SettingActivity.this, "人脸注册阈值必须为0~100之间", Toast.LENGTH_SHORT).show();
                    return;
                }
                SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();
                editor.putFloat("faceAccuracy", Float.parseFloat(etFace.getText().toString().trim()));
                editor.apply();

                EditText idEdit = findViewById(R.id.boxid);
                String id = idEdit.getText().toString();
                _sn = id;
                new FetchgetCabinetType(id).execute();
            }
        });


        Button sys_btn = (Button) findViewById(R.id.sysbtn);
        sys_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(android.provider.Settings.ACTION_SETTINGS);
                startActivity(intent);
            }
        });


        Button face_btn = (Button) findViewById(R.id.facebtn);
        face_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();
                editor.putString("face_active","2020-05-01");
                editor.apply();
            }
        });

        Button orientation_btn = (Button) findViewById(R.id.orientationbtn);
        orientation_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences sharedPreferences = getSharedPreferences("xbbox", Context.MODE_PRIVATE);
                String orientation = sharedPreferences.getString("Orientation","");
                Log.e("Orientation=====", orientation);
                if (orientation.equals("landscape")) {
                    SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();
                    editor.putString("Orientation","portrait");
                    editor.apply();
                } else {
                    SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();
                    editor.putString("Orientation","landscape");
                    editor.apply();
                }

                runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Exit();
                            OtherUtil.restartApplication(SettingActivity.this);
                        }
                    }, 1000);
                }
            });

            }
        });

        Button re_btn = (Button) findViewById(R.id.rebtn);
        re_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (etFace.getText().toString().trim().equals("") || Float.parseFloat(etFace.getText().toString().trim()) > 100f) {
                    Toast.makeText(SettingActivity.this, "人脸注册阈值必须为0~100之间", Toast.LENGTH_SHORT).show();
                    return;
                }
                SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();
                editor.putFloat("faceAccuracy", Float.parseFloat(etFace.getText().toString().trim()));
                editor.apply();

                Exit();
                finish();
            }
        });
        hideBottomUIMenu();
        if(OtherUtil.isExistUID(this)){
            _sn = OtherUtil.getUID(this);
            EditText idEdit = findViewById(R.id.boxid);
            idEdit.setText(_sn);
            initTimer();
        }
    }
    private void initTimer(){
        if (mTimer == null) {
            mTimer = new CountDownTimer((long) (240 * 1000), 1000) {

                @Override
                public void onTick(long millisUntilFinished) {
                    if (!SettingActivity.this.isFinishing()) {
                        int remainTime = (int) (millisUntilFinished / 1000L);
                        Log.e("zpan", "======remainTime=====" + remainTime);

                        count --;
                        if(count < 1){
                            Exit();
                            finish();
                        }

                    }
                }

                @Override
                public void onFinish() {
                    Log.e("zpan", "======onFinish=====");
                }
            };
            mTimer.start();
        }
    }
    private void unInitTimer(){
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }
    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {

            Window _window = getWindow();
            WindowManager.LayoutParams params = _window.getAttributes();
            params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE;
            _window.setAttributes(params);
        }
    }
    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        // Trigger the initial hide() shortly after the activity has been
        // created, to briefly hint to the user that UI controls
        // are available.
        delayedHide(100);
    }

    private void toggle() {
        if (mVisible) {
            hide();
        } else {
            show();
        }
    }

    private void hide() {
        // Hide UI first
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        mVisible = false;


    }

    @SuppressLint("InlinedApi")
    private void show() {
        mVisible = true;

    }

    /**
     * Schedules a call to hide() in delay milliseconds, canceling any
     * previously scheduled calls.
     */
    private void delayedHide(int delayMillis) {
        mHideHandler.removeCallbacks(mHideRunnable);
        mHideHandler.postDelayed(mHideRunnable, delayMillis);
    }

    private void Exit(){
        EventBus.getDefault().unregister(this);
    }
    @Override
    protected void onDestroy() {
        //unInitTimer();

        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN,priority = 100,sticky = false)     //在UI线程执行，100  为优先级
    public void onEvent(Message message){
        Intent intent = new Intent();
        switch(message.what){
            case 10000:
                handleGetCabinetType(message.obj);
                break;
            case 10001:
                Toast.makeText(SettingActivity.this, "获取柜子类型失败", Toast.LENGTH_SHORT).show();
                break;

        }
    }
    private void handleGetCabinetType(Object obj){
        try{
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
                OtherUtil.setUID(SettingActivity.this,_sn);
                String phone = result.getJSONObject("data").getString("phone");
                String kuai = result.getJSONObject("data").getString("kuai");
                String cai = result.getJSONObject("data").getString("cai");
                String address = result.getJSONObject("data").getString("address");
                String serviceline = result.getJSONObject("data").getString("serviceline");
                SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();
                editor.putString("CabinetType_phone",phone);

                editor.putString("CabinetType_kuai",kuai);
                editor.putString("CabinetType_cai",cai);
                editor.putString("CabinetType_address",address);
                editor.putString("CabinetType_serviceline",serviceline);
                editor.apply();

                Intent intent = new Intent();
                setResult(1000, intent);
                Exit();
                finish();
            }else{
                View cv = getWindow().getDecorView();
                AlertDialog.Builder adbuilder = new AlertDialog.Builder(cv.getContext());
                adbuilder.setTitle(result.getString("msg"));
                adbuilder.setMessage("2秒后自动关闭！");
                adbuilder.setCancelable(true);
                final AlertDialog dlg = adbuilder.create();
                dlg.show();
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        dlg.dismiss();
                        t.cancel();
                    }
                }, 2000);
            }
        }
        catch (Exception e){
            Log.d("handleSendGridTask",e.toString());
        }
    }

}
